<template>
  <div class="header-container">
    <nav-bar
      :title="title"
      :showLeftArrow="true"
      :leftText="'返回'"
      @click-left="back"
    >
    </nav-bar>
  </div>
  <div class="main-container">
    <van-address-edit
      :area-list="areaList"
      :address-info="vantAddr"
      show-detail
      show-set-default
      show-area
      :show-delete="operation == 'EDIT'"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @delete="onDelete"
      @save="onSave"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import NavBar from "@/components/NavBar.vue";
import TabBar from "@/components/TabBar.vue";
import { useRoute, useRouter } from "vue-router";
import { AxiosError } from "axios";
import { AddressEditInfo, Dialog, Toast } from "vant";
import addressService from "@/services/address.service";
import UmsAddress from "@/entity/UmsAddress";
import OperationType from "@/entity/OperationType";
import regionService from "@/services/region.service";

type StateType = {
  title: string;
  areaList: any;
  addr: UmsAddress;
  vantAddr?: AddressEditInfo;
  id?: number;
  operation?: OperationType;
};

export default defineComponent({
  components: {
    NavBar,
    TabBar,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive<StateType>({
      title: "",
      areaList: regionService.vantAreaList(),
      addr: new UmsAddress(),
      vantAddr: undefined,
      id: undefined,
      operation: undefined,
    });

    onMounted(async () => {
      state.operation = route.query.operation as OperationType | undefined;
      state.id = route.query.id != null ? Number(route.query.id) : undefined;

      if (state.operation == OperationType.CREATE) {
        create();
      } else if (state.operation == OperationType.EDIT) {
        edit();
      }
    });

    const create = () => {
      state.title = "新增地址";
    };
    const edit = () => {
      state.title = "修改地址";
      if (state.id != null) {
        load(Number(state.id));
      }
    };

    const load = async (id: number) => {
      try {
        const addr = await addressService.retrieve(id);
        state.addr = addr;
        if (state.addr) {
          state.vantAddr = {
            // id: state.addr.id != null ? state.addr.id : 0,
            tel:
              state.addr.receiverPhone != null ? state.addr.receiverPhone : "",
            name:
              state.addr.receiverName != null ? state.addr.receiverName : "",
            country: "中国",
            province:
              state.addr.receiverProvince != null
                ? state.addr.receiverProvince
                : "",
            city:
              state.addr.receiverCity != null ? state.addr.receiverCity : "",
            county:
              state.addr.receiverDistrict != null
                ? state.addr.receiverDistrict
                : "",
            addressDetail:
              state.addr.receiverAddress != null
                ? state.addr.receiverAddress
                : "",
            areaCode:
              state.addr.receiverDistrictCode != null
                ? state.addr.receiverDistrictCode
                : "",
            postalCode:
              state.addr.receiverDistrictCode != null
                ? state.addr.receiverDistrictCode
                : "",
            isDefault: false,
          };
        }
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const back = () => {
      router.back();
    };

    const onSave = async (content: AddressEditInfo) => {
      state.addr.receiverName = content.name;
      state.addr.receiverPhone = content.tel;
      state.addr.receiverProvinceCode =
        content.areaCode.substring(0, 2) + "0000";
      state.addr.receiverProvince = content.province;
      state.addr.receiverCityCode = content.areaCode.substring(0, 4) + "00";
      state.addr.receiverCity = content.city;
      state.addr.receiverDistrictCode = content.areaCode;
      state.addr.receiverDistrict = content.county;
      state.addr.receiverAddress = content.addressDetail;

      try {
        let id = -1;
        if (state.operation == OperationType.CREATE) {
          id = await addressService.create(state.addr);
        } else {
          id = await addressService.update(state.addr);
        }
        Toast.success("保存成功");
        router.push({
          path: "/address",
          query: {
            ...route.query,
          },
        });
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("保存失败");
        throw e;
      } finally {
      }
    };

    const onDelete = async () => {
      Dialog.confirm({
        message: "确定要删除这条数据吗",
      })
        .then(async () => {
          try {
            await addressService.remove(
              state.addr.id != null ? [state.addr.id] : []
            );
            Toast.success("删除成功");
            router.push({
              path: "/address",
              query: {
                ...route.query,
              },
            });
          } catch (e) {
            if (e instanceof AxiosError && e.response?.status == 401) {
              Toast.fail("请先登录");
              router.push("/login");
              return;
            }
            Toast.fail("删除失败");
            throw e;
          } finally {
          }
        })
        .catch(() => {});
    };

    return {
      ...toRefs(state),
      back,
      onSave,
      onDelete,
    };
  },
});
</script>

<style scoped></style>
